<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目ID" prop="projectId">
        <el-input
          v-model="queryParams.projectId"
          placeholder="请输入项目ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务编号" prop="taskCode">
        <el-input
          v-model="queryParams.taskCode"
          placeholder="请输入任务编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
          <el-option
            v-for="dict in task_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable>
          <el-option label="高" value="0" />
          <el-option label="中" value="1" />
          <el-option label="低" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择计划开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择计划结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['erp:task:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['erp:task:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['erp:task:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['erp:task:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Plus"
          @click="handleBatchAdd"
          v-hasPermi="['erp:task:batchAddTasks']"
        >批量添加任务</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="taskList" 
      @selection-change="handleSelectionChange"
      class="task-table"
      stripe
      border
      :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: '600' }"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="项目ID" align="center" prop="projectId" width="120" show-overflow-tooltip>
        <template #default="scope">
          <div class="project-info">
            <el-icon class="project-icon"><Folder /></el-icon>
            <span>{{ scope.row.projectId || '暂无' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="任务编号" align="center" prop="taskCode" width="120" show-overflow-tooltip />
      <el-table-column label="任务名称" align="left" prop="taskName" min-width="150" show-overflow-tooltip>
        <template #default="scope">
          <div class="task-name">
            <el-icon class="task-icon"><Document /></el-icon>
            <span class="task-title">{{ scope.row.taskName || '暂无' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="任务描述" align="left" prop="taskDesc" min-width="200" show-overflow-tooltip>
        <template #default="scope">
          <div class="desc-info" v-if="scope.row.taskDesc">
            <el-icon class="desc-icon"><Reading /></el-icon>
            <span class="desc-text">{{ scope.row.taskDesc }}</span>
          </div>
          <span v-else class="text-muted">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="status" width="120">
        <template #default="scope">
          <dict-tag :options="task_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority" width="100">
        <template #default="scope">
          <el-tag 
            :type="getPriorityType(scope.row.priority)" 
            :effect="getPriorityEffect(scope.row.priority)"
            class="priority-tag"
          >
            {{ getPriorityText(scope.row.priority) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="120">
        <template #default="scope">
          <div class="date-info" v-if="scope.row.startTime">
            <el-icon class="date-icon"><Calendar /></el-icon>
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
          </div>
          <span v-else class="text-muted">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="120">
        <template #default="scope">
          <div class="date-info" v-if="scope.row.endTime">
            <el-icon class="date-icon"><Calendar /></el-icon>
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </div>
          <span v-else class="text-muted">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="left" prop="remark" width="150" show-overflow-tooltip>
        <template #default="scope">
          <span class="remark-text">{{ scope.row.remark || '暂无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            icon="Edit" 
            @click="handleUpdate(scope.row)" 
            v-hasPermi="['erp:task:edit']"
            class="action-btn"
          >
            修改
          </el-button>
          <el-button 
            link 
            type="danger" 
            icon="Delete" 
            @click="handleDelete(scope.row)" 
            v-hasPermi="['erp:task:remove']"
            class="action-btn"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 批量添加任务对话框 -->
    <el-dialog title="批量添加任务到所有项目" v-model="batchOpen" width="500px" append-to-body>
      <el-form ref="batchFormRef" :model="batchForm" :rules="batchRules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="batchForm.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务描述" prop="taskDesc">
          <el-input v-model="batchForm.taskDesc" type="textarea" placeholder="请输入任务描述" :rows="3" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-radio-group v-model="batchForm.priority">
            <el-radio label="0">高</el-radio>
            <el-radio label="1">中</el-radio>
            <el-radio label="2">低</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitBatchForm">确 定</el-button>
          <el-button @click="cancelBatch">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改任务对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="taskRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目ID" prop="projectId">
          <el-input 
            v-model="form.projectId" 
            placeholder="请输入项目ID"
            @input="handleProjectIdChange"
          />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input 
            v-model="form.projectName" 
            placeholder="请输入项目名称"
          />
        </el-form-item>
        <el-form-item label="任务编号" prop="taskCode">
          <el-input 
            v-model="form.taskCode" 
            placeholder="任务编号将自动生成"
            readonly
            class="readonly-input"
          />
        </el-form-item>
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务描述" prop="taskDesc">
          <el-input v-model="form.taskDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="任务状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in task_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-radio-group v-model="form.priority">
            <el-radio label="0">高</el-radio>
            <el-radio label="1">中</el-radio>
            <el-radio label="2">低</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择计划开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择计划结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Task">
import { listTask, getTask, delTask, addTask, updateTask, batchAddToAllProjects } from "@/api/erp/task"
import { Document, Calendar, Folder, Reading } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const { task_status } = proxy.useDict('task_status')

const taskList = ref([])
const open = ref(false)
const batchOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: null,
    taskCode: null,
    taskName: null,
    taskDesc: null,
    status: null,
    priority: null,
    startTime: null,
    endTime: null,
  },
  rules: {
    projectId: [
      { required: true, message: "项目ID不能为空", trigger: "blur" }
    ],
  },
  batchForm: {
    taskName: '',
    taskDesc: '',
    priority: '1'
  },
  batchRules: {
    taskName: [
      { required: true, message: "任务名称不能为空", trigger: "blur" }
    ],
    priority: [
      { required: true, message: "优先级不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules, batchForm, batchRules } = toRefs(data)

/** 查询任务列表 */
function getList() {
  loading.value = true
  listTask(queryParams.value).then(response => {
    taskList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectId: null,
    projectName: null,
    taskCode: null,
    taskName: null,
    taskDesc: null,
    status: null,
    priority: null,
    startTime: null,
    endTime: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("taskRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加任务"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getTask(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改任务"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["taskRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateTask(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addTask(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除任务编号为"' + _ids + '"的数据项？').then(function() {
    return delTask(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('erp/task/export', {
    ...queryParams.value
  }, `task_${new Date().getTime()}.xlsx`)
}

/** 获取优先级文本 */
function getPriorityText(priority) {
  const priorityMap = {
    0: '高',
    1: '中', 
    2: '低'
  }
  return priorityMap[priority] || '未知'
}

/** 获取优先级标签类型 */
function getPriorityType(priority) {
  const typeMap = {
    0: 'danger',  // 高优先级 - 红色
    1: 'warning', // 中优先级 - 橙色
    2: 'info'     // 低优先级 - 蓝色
  }
  return typeMap[priority] || ''
}

/** 获取优先级标签效果 */
function getPriorityEffect(priority) {
  return priority === 0 ? 'dark' : 'plain'
}

/** 批量添加任务按钮操作 */
function handleBatchAdd() {
  resetBatchForm()
  batchOpen.value = true
}

/** 批量添加表单重置 */
function resetBatchForm() {
  batchForm.value = {
    taskName: '',
    taskDesc: '',
    priority: '1'
  }
  proxy.resetForm("batchFormRef")
}

/** 取消批量添加 */
function cancelBatch() {
  batchOpen.value = false
  resetBatchForm()
}

/** 提交批量添加表单 */
function submitBatchForm() {
  proxy.$refs["batchFormRef"].validate(valid => {
    if (valid) {
      proxy.$modal.confirm('确认要为所有项目批量添加此任务吗？').then(function() {
        // 构建请求数据，不包含 status 字段
        const requestData = {
          taskName: batchForm.value.taskName,
          taskDesc: batchForm.value.taskDesc,
          priority: batchForm.value.priority
        }
        return batchAddToAllProjects(requestData)
      }).then(() => {
        proxy.$modal.msgSuccess("批量添加成功")
        batchOpen.value = false
        resetBatchForm()
        getList()
      }).catch(() => {})
    }
  })
}

/** 处理项目ID变化 */
function handleProjectIdChange() {
  if (!form.value.projectId) {
    // 如果项目ID为空，清空任务编号
    form.value.taskCode = ''
    return
  }

  if (form.value.taskCode) {
    // 如果已有任务编号，更新前缀
    const parts = form.value.taskCode.split('-')
    if (parts.length >= 2) {
      // 保留序号部分，更新项目ID前缀
      const taskNumber = parts.slice(1).join('-')
      form.value.taskCode = `${form.value.projectId}-${taskNumber}`
    } else {
      // 如果没有序号部分，生成默认格式
      form.value.taskCode = `${form.value.projectId}-001`
    }
  } else {
    // 如果没有任务编号，生成默认任务编号
    // 这里可以根据实际需求调用后端API获取下一个序号
    form.value.taskCode = `${form.value.projectId}-001`
  }
}

getList()
</script>

<style scoped>
/* 表格样式优化 */
.task-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.task-table :deep(.el-table__body-wrapper) {
  border-radius: 0 0 8px 8px;
}

.task-table :deep(.el-table__header-wrapper) {
  border-radius: 8px 8px 0 0;
}

.task-table :deep(.el-table__row) {
  transition: all 0.3s ease;
}

.task-table :deep(.el-table__row:hover) {
  background-color: #f8f9fa !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 项目信息样式 */
.project-info {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.project-icon {
  color: #409eff;
  font-size: 16px;
}

/* 任务名称样式 */
.task-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.task-icon {
  color: #67c23a;
  font-size: 16px;
}

.task-title {
  font-weight: 500;
  color: #303133;
}

/* 描述信息样式 */
.desc-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.desc-icon {
  color: #909399;
  font-size: 14px;
  flex-shrink: 0;
}

.desc-text {
  color: #606266;
  font-size: 13px;
  line-height: 1.4;
}

/* 日期信息样式 */
.date-info {
  display: flex;
  align-items: center;
  gap: 4px;
  justify-content: center;
}

.date-icon {
  color: #67c23a;
  font-size: 14px;
}

/* 备注文本样式 */
.remark-text {
  color: #909399;
  font-size: 13px;
  font-style: italic;
}

/* 暂无文本样式 */
.text-muted {
  color: #c0c4cc;
  font-size: 12px;
  font-style: italic;
}

/* 操作按钮样式 */
.action-btn {
  margin: 0 2px;
  font-size: 12px;
  padding: 4px 8px;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 状态标签优化 */
.task-table :deep(.el-tag) {
  border-radius: 12px;
  font-weight: 500;
}

/* 优先级标签样式 */
.priority-tag {
  font-weight: 600;
  font-size: 12px;
  border-radius: 16px;
  padding: 4px 12px;
  min-width: 40px;
  text-align: center;
}

.priority-tag.el-tag--danger {
  background: linear-gradient(135deg, #f56c6c, #e6a23c);
  border: none;
  color: white;
  box-shadow: 0 2px 4px rgba(245, 108, 108, 0.3);
}

.priority-tag.el-tag--warning {
  background: linear-gradient(135deg, #e6a23c, #f7ba2a);
  border: none;
  color: white;
  box-shadow: 0 2px 4px rgba(230, 162, 60, 0.3);
}

.priority-tag.el-tag--info {
  background: linear-gradient(135deg, #909399, #b3b6bb);
  border: none;
  color: white;
  box-shadow: 0 2px 4px rgba(144, 147, 153, 0.3);
}

/* 只读输入框样式 */
.readonly-input :deep(.el-input__wrapper) {
  background-color: #f5f7fa !important;
  border-color: #dcdfe6 !important;
  color: #909399 !important;
  cursor: not-allowed !important;
}

.readonly-input :deep(.el-input__inner) {
  background-color: transparent !important;
  color: #909399 !important;
  cursor: not-allowed !important;
}

.readonly-input :deep(.el-input__wrapper:hover) {
  border-color: #dcdfe6 !important;
  box-shadow: none !important;
}

.readonly-input :deep(.el-input__wrapper:focus-within) {
  border-color: #dcdfe6 !important;
  box-shadow: none !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .task-table :deep(.el-table__header-wrapper),
  .task-table :deep(.el-table__body-wrapper) {
    font-size: 12px;
  }
  
  .task-name {
    flex-direction: column;
    gap: 4px;
  }
  
  .project-info {
    flex-direction: column;
    gap: 4px;
  }
  
  .desc-info {
    flex-direction: column;
    gap: 4px;
    align-items: flex-start;
  }
}
</style>
